var fs = require('fs');
var path = require('path');
function readFile(filename) {
  return fs.readFileSync(path.join(__dirname, filename), 'utf-8');
}
var last = Date.now();
var config = {};

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
function refreshConfig() {
  if (Date.now() - last < 1000) {
    last = Date.now();
    return;
  }
  last = Date.now();
  config = JSON.parse(readFile('config.js'));
}

function parsePattern(pattern) {
  if (
    pattern.indexOf('/') == 0 && 
    (
      pattern.lastIndexOf('/') == pattern.length - 1 ||
      pattern.lastIndexOf('/') == pattern.length - 2
    )
  ) {
    return eval('(' + pattern + ')');;
  }
  return {test: t => t.indexOf(pattern) > -1 };
}

refreshConfig();

// docs: http://anyproxy.io/4.x/

module.exports = {
  // 模块介绍
  summary() { return 'xijin customized rule for AnyProxy'; }, 
  // 发送请求前拦截处理
  *beforeSendRequest(requestDetail) {
    console.log('bsr');
    refreshConfig();
    const returnDirectConfig = config['return-direct'] || [];
    const url = requestDetail.url;
    for (let config of returnDirectConfig) {
      var pattern = parsePattern(config.pattern);
      if (pattern.test(url)) {
        console.log('find match for ' + url);
        content = config.content;
        var h = (content.indexOf('{') == 0) ? 
          {"content-type":"application/json;charset=utf-8"} : {"content-type": 'text/html'} ;
        return {
					response: {
						statusCode: 200,
						header: h,
						body: content,
					}
        };
			}
    }
		return null;
	}, 
  // 发送响应前处理
  *beforeSendResponse(requestDetail, responseDetail) { return null; }, 
  // 是否处理https请求
  *beforeDealHttpsRequest(requestDetail) {
    /*
     * requestDetail
     * host {string} 请求目标的Host，受制于协议，这里无法获取完整url
     * _req {object} 请求的原始request
     */
    console.log('bd--https:', requestDetail.host);
    return true;
  }, 
  // 请求出错的事件
  *onError(requestDetail, error) {
    console.log("on error", error);
    return null;
  }, 
  // https连接服务器出错
  *onConnectError(requestDetail, error) {
    console.log("https error", error);
    return null;
  } 
};
